import React from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import type {ActionType} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import util from '@/utils';
import {Button, message, Popconfirm} from 'antd';
import XLSX from 'xlsx';

const queryList = async (params?: any) => {
   const {data} = await util.request({
      url: '/warehouse',
      method: 'GET',
      params: params
   });
   return data as Array<any>;
};


const saveData = async (data: any) => {
   const response = await util.request({
      url: `/warehouse`,
      method: 'POST',
      data: data
   });
   return response;
};

const deleteById = async (id: number) => {
   const response = await util.request({
      url: `/warehouse/${id}`,
      method: 'DELETE'
   });
   return response;
};


export default function Warehouse() {

   const tabActiveKeyState = React.useState<string>('base');

   const actionRef = React.useRef<ActionType>();

   return <PageContainer
      className='page-container'
      tabList={[{tab: '基本信息', key: 'base'}]}
      tabActiveKey={tabActiveKeyState[0]}
      extra={[
         <Button type='primary' onClick={() => {
            actionRef.current?.addEditRecord?.({});
         }}>
            添加
         </Button>
      ]}
   >
      <ProTable
         bordered
         size='small'
         tableAlertRender={({selectedRowKeys, selectedRows}) => {
            return [
               <>已选择{selectedRowKeys.length}项</>,
               <Button type='link' onClick={() => {
                  const loading = message.loading('请稍等,生成中...');
                  selectedRows = selectedRows.map(res => {
                     return {
                        '编号': res.id,
                        '名称': res.name,
                        '单位': res.unit,
                        '单价': res.unitPrice,
                        '申请数量': res.applyNumber,
                        '实购数量': res.actualNumber,
                        '金额': res.totalPrice,
                        '备注': res.note,
                        '处理时间': new Date(res.time).toLocaleString()
                     };
                  });
                  const ws = XLSX.utils.json_to_sheet(selectedRows);
                  const wb = XLSX.utils.book_new();
                  XLSX.utils.book_append_sheet(wb, ws, '货物统计');
                  XLSX.writeFile(wb, '货物统计' + new Date().toLocaleString() + '.xlsx');
                  loading();
               }}>导出Excel</Button>
            ];
         }}
         rowSelection={{}}
         actionRef={actionRef}
         scroll={{x: 1500}}
         editable={{
            type: 'single',
            onSave: async (rowKey, data, row) => {
               await saveData(data);
               message.success('修改成功', 0.8);
            },
            onDelete: async (key, row) => {
               await deleteById(key as number);
               message.success('删除成功', 0.8);
            }
         }}
         columns={[
            {
               title: '编号',
               valueType: 'index',
               editable: false,
               width: 60,
               fixed: 'left'
            },
            {
               dataIndex: 'name',
               title: '名称',
               copyable: true,
               fixed: 'left',
               width: 120
            },
            {
               dataIndex: 'unit',
               title: '单位',
               search: false
            },
            {
               dataIndex: 'applyNumber',
               title: '申请数量',
               valueType: 'digit'
            },
            {
               dataIndex: 'actualNumber',
               title: '实够数量',
               valueType: 'digit'
            },
            {
               dataIndex: 'unitPrice',
               title: '单价',
               valueType: 'digit'
            },
            {
               dataIndex: 'totalPrice',
               title: '金额',
               valueType: 'digit'
            },
            {
               dataIndex: 'time',
               title: '操作时间',
               valueType: 'dateTime',
               width: 180
            },
            {
               dataIndex: 'note',
               title: '备注',
               width: 220,
               ellipsis: true,
               copyable: true
            },
            {
               title: '操作',
               key: 'action',
               width: 150,
               search: false,
               fixed: 'right',
               valueType: 'option',
               render: (text, record, _, action) => [
                  <Popconfirm
                     title='确定删除吗?'
                     onConfirm={async () => {
                        await deleteById(record.id);
                        message.success('删除成功', 0.8);
                        action?.reload();
                     }}
                     okText='Yes'
                     cancelText='No'
                  >
                     <Button type='link' danger>删除</Button>
                  </Popconfirm>,
                  <Button onClick={() => {
                     action?.startEditable?.(record.id);
                  }} type='link'>修改</Button>
               ]
            }
         ]}
         search={{span: 6}}
         request={async (params) => {
            const data = await queryList(params);
            return Promise.resolve({
               data: data,
               success: true,
               total: data.length
            });
         }}
         options={{
            density: true,
            fullScreen: true,
            setting: true
         }}
         footer={(data) => {
            const totalPrice = data.reduce((previousValue, current) => {
               return previousValue + current.totalPrice;
            }, 0);
            return <>总价：{totalPrice || 0}元</>;
         }}
         rowKey='id'
      />
   </PageContainer>;
};
